package lq.common.configure;

import feign.RequestInterceptor;
import lq.common.entity.StudyConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;

/**
 * @program: cloud-study
 * feign 配置
 * 拦截
 * @description:
 * @author: LQ
 * @create: 2020-10-26 10:36
 */

public class StudyOAuth2FeignConfigure {

    /**
     * 拦截Feign请求，手动往请求头上加入令牌
     * 们通过SecurityContextHolder从请求上下文中获取了OAuth2AuthenticationDetails类型对象
     * 并通过OAuth2AuthenticationDetails对象获取到了请求令牌
     * 然后在请求模板对象requestTemplate的头部手动将令牌添加上去
     *
     * @return
     */
    @Bean
    public RequestInterceptor oAuth2FeignConfigure() {
        return requestTemplate -> {
            // 添加Zuul Token
            String zuulToken = new String(Base64Utils.encode(StudyConstant.ZUUL_TOKEN_VALUE.getBytes()));
            requestTemplate.header(StudyConstant.ZUUL_TOKEN_HEADER, zuulToken);

            Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
            if (details instanceof OAuth2AuthenticationDetails) {
                String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                requestTemplate.header(HttpHeaders.AUTHORIZATION, "bearer " + authorizationToken);
            }
        };
    }
}
